package com.wan37.gate.domain;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 客户端连接的封装类。
 *
 * @author : luoyong
 * @date : 2020-05-26 16:43
 **/
public class ClientConnection {

    private static final Logger logger = LoggerFactory.getLogger(ClientConnection.class);

    public static AttributeKey<Long> NETID = AttributeKey.valueOf("netId");

    public static AttributeKey<String> SCENEID = AttributeKey.valueOf("sceneId");

    public static final AtomicLong netIdGenerator = new AtomicLong(0);

    private String userId;
    private long netId;
    private ChannelHandlerContext ctx;

    public ClientConnection(ChannelHandlerContext ctx) {

        //为当前对象生成唯一netId
        this.netId = ClientConnection.netIdGenerator.incrementAndGet();
        ;
        this.ctx = ctx;
        //向channel中添加属性NETID = netId
        this.ctx.channel().attr(ClientConnection.NETID).set(this.netId);
        logger.info("新接入的客户端netId = ", this.netId);
    }

    public String getUserId() {
        return userId;
    }

    public long getNetId() {
        return netId;
    }

    public ChannelHandlerContext getCtx() {
        return ctx;
    }

    public ClientConnection setUserId(String userId) {
        this.userId = userId;
        return this;
    }

    public ClientConnection setCtx(ChannelHandlerContext ctx) {
        this.ctx = ctx;
        return this;
    }


    @Override
    public String toString() {
        return "ClientConnection{" +
                "userId='" + userId + '\'' +
                ", netId=" + netId +
                ", ctx=" + ctx +
                '}';
    }
}

